
var AiOS_Addons = {};

(function() {
    // Registration
    var namespaces = [];

    this.ns = function(fn) {
        var ns = {};
        namespaces.push(fn, ns);
        return ns;
    };

    // Initialization
    this.initialize = function() {

        for (var i=0; i<namespaces.length; i+=2) {
            var fn = namespaces[i];

            var ns = namespaces[i+1];
            fn.apply(ns);
        }

        var debug = false;

        var in_sidebar = (top.document.getElementById('sidebar-box') || debug) ? true : false;
        if(in_sidebar) {
            // für CSS-Zwecke speichern
            aios_appInfo(document.getElementById("addons-page"));

            // CSS-Datei einbinden
            aios_addCSS("addons.css", document.getElementById("addons-page"));
            
            AiOS_Addons.setSidebarLayout();
            AiOS_Addons.checkNotification();

            // without the timeout the childNodes.length of "addon-list" will be 0
            window.setTimeout("AiOS_Addons.countElements()", 500);
        }

        // sorgt dafür, dass bei neuen Downloads oder neuen Add-on-Installationen der Titel aktualisiert wird
        /*try {
            window.addEventListener("DOMNodeInserted", AiOS_Addons.countElements, true);
            window.addEventListener("DOMNodeRemoved", AiOS_Addons.countElements, true);
            window.addEventListener("DOMAttrModified", function(e){
                if(e.originalTarget.tagName == "richlistitem" && e.attrName == "state") {
                    //alert(e.attrName);
                    if(e.originalTarget.getAttribute('state') == "1") {
                        AiOS_Addons.countElements();
                    }
                }
            }, true);
        } catch(ex) { }*/

        

    };

    
    this.setSidebarLayout = function() {

        var before, insertedElement;

        // Navigation horizontal ausrichten
        var nav_tmp = document.getElementById("category-search").parentNode;
        var nav = nav_tmp.ownerDocument.getAnonymousNodes(nav_tmp);
        nav[0].setAttribute("orient", "horizontal");
        nav[0].setAttribute("style", "overflow:hidden;");

        // Toolbar mit Suchfeld usw. verschieben
        before = document.getElementById("view-port-container");
        insertedElement = before.parentNode.insertBefore(document.getElementById("header"), before);

        // Label bei Suche ohne Suchergebnisse kürzen
        document.getElementById("search-list-empty").childNodes[1].childNodes[0].setAttribute("crop", "end");

        // Container mit Update-Meldungen verschieben => ansonsten werden die Meldungen im Header angezeigt
        before = document.getElementById("view-port-container");
        insertedElement = before.parentNode.insertBefore(document.getElementById("updates-container"), before);

        // Inhalt der gelben Notificationbox vertikal anordnen
        var updatesBox = document.createElement("vbox");
        updatesBox.setAttribute("align", "left");
        updatesBox.appendChild(document.getElementById("updates-downloaded"));
        updatesBox.appendChild(document.getElementById("updates-restart-btn"));
        document.getElementById("updates-container").insertBefore(updatesBox, document.getElementById("updates-container").childNodes[5]);

        // Navigationsbuttons immer sichtbar machen
        document.getElementById('back-btn').setAttribute('hidden', false);
        document.getElementById('forward-btn').setAttribute('hidden', false);

    };



    this.setDetailLayout = function() {

        // Detail-Ansicht: Buttons in der Pending-Box (Updateinstallation) rechts ausrichten und vertikal anordnen
        var pending = document.getElementById("pending-container");
        pending.setAttribute("align", "left");
        var pendingBox = document.createElement("vbox");
        pendingBox.setAttribute("align", "end");
        pendingBox.appendChild(document.getElementById("detail-restart-btn"));
        pendingBox.appendChild(document.getElementById("detail-undo-btn"));
        pending.appendChild(pendingBox);

        // neue Anordnung des Headerbereichs der Detail-Ansicht
        var summary = document.getElementById("detail-summary");
        var newParent = summary.parentNode;
        var hbox = document.createElement("hbox");
        hbox.setAttribute("id", "detail-header");
        hbox.setAttribute("align", "left"); // Icons werden nicht verzerrt, wenn sie nicht 64x64 sind
        hbox.appendChild(document.getElementById("detail-icon"));
        hbox.appendChild(summary);
        newParent.insertBefore(hbox, document.getElementById("detail-desc-container"));

        // Name über der Versionsnummer platzieren
        summary.insertBefore(document.getElementById("detail-name"), document.getElementById("detail-name-container"));

        // Screenshot verschieben
        var screenshot = document.getElementById("detail-screenshot").parentNode;
        screenshot.setAttribute("align", "left"); // Bild wird nicht verzerrt
        var descContainer = document.getElementById("detail-desc-container");
        descContainer.childNodes[1].insertBefore(screenshot, document.getElementById("detail-fulldesc"));
        //descContainer.childNodes[1].appendChild(descContainer.childNodes[0]);detail-screenshot

        // Detail-Ansicht: Buttons in der Spenden-Box rechts ausrichten
        document.getElementById("detail-contributions").childNodes[1].removeAttribute("align");

    };

    
    // gelbe Notification-Box abhängig von vorhandenen Notifications ein- oder ausblenden
    this.checkNotification = function() {

        if( !document.getElementById('updates-noneFound').hidden ||
            !document.getElementById('updates-manualUpdatesFound-btn').hidden ||
            !document.getElementById('updates-progress').hidden ||
            !document.getElementById('updates-installed').hidden ||
            !document.getElementById('updates-downloaded').hidden ||
            !document.getElementById('updates-restart-btn').hidden) {

            document.getElementById('updates-container').hidden = false;
        }
        else {
            document.getElementById('updates-container').hidden = true;
        }

    };


    // gelbe Notification-Box ausblenden
    this.hideNotification = function() {

        document.getElementById('updates-container').hidden = true;

    };


    // Elemente zählen und anzeigen
    this.countElements = function() {

        // bisherigen Titel feststellen
        var origTitle, newTitle;
        if(aios_WIN.document.getElementById("viewAddonsSidebar")) origTitle = aios_WIN.document.getElementById("viewAddonsSidebar").getAttribute('label');

        // originalen Titel um das aktivierte Panel erweitern
        if(document.getElementById("categories") && document.getElementById("categories").selectedItem) {
            var viewTitle = document.getElementById("categories").selectedItem.getAttribute('name');
            origTitle = origTitle + " - " + viewTitle;
        }
        newTitle = origTitle;
        
        /*
        category-search             => search-list
        category-discover           => -
        category-languages          => addon-list
        category-searchengines      => addon-list
        category-extensions         => addon-list
        category-themes             => addon-list
        category-plugins            => addon-list
        category-availableUpdates   => updates-list
        category-recentUpdates      => updates-list
        category-scripts            => addon-list
        */
        var count = true;
        var selected = document.getElementById('categories').getAttribute('last-selected');
        var in_sidebar = (top.document.getElementById('sidebar-box')) ? true : false;
        if(!aios_gPrefBranch.getBoolPref("em.count") || !in_sidebar || selected == "category-discover") count = false;
                
        if(count) {
            var type = "all";
            var the_list = "addon-list";
            if(selected == "category-search") {
                the_list = "search-list";
                type = document.getElementById("search-filter-radiogroup").getAttribute("value");
            }
            if(selected == "category-availableUpdates" || selected == "category-recentUpdates") the_list = "updates-list";
            
            var exts = this.filterItems(the_list, type);
            var str_count;
            var list_enabled = 0;
            var list_disabled = 0;

            for(var i = 0; i < exts.length; i++) {
                if(exts[i].getAttribute('active') == "true") list_enabled++;
                else  list_disabled++;
            }

            str_count = list_enabled;
            if(list_disabled > 0) str_count = str_count + "/" + list_disabled;
            
            // neuen Titel erzeugen
            newTitle = origTitle + " [" + str_count + "]";
            document.title = newTitle;  // Titel und Label setzen
        }

        // neuen Titel setzen
        if(top.document.getElementById('sidebar-title')) top.document.getElementById('sidebar-title').setAttribute("value", newTitle);

        // Sidebartitel im Broadcaster speichern, damit er beim Schließen/öffnen der Sidebar wiederhergestellt werden kann
        if(top.document.getElementById('viewAddonsSidebar')) top.document.getElementById('viewAddonsSidebar').setAttribute('sidebartitle', newTitle);

        return true;
        
    };


    // Richlistitems filtern
    this.filterItems = function(aList, aType) {

        var r = [];

        var childs = document.getElementById(aList).childNodes;
        
        for(var i = 0; i < childs.length; i++) {
            if(childs[i].nodeName == "richlistitem" && childs[i].getAttribute('hidden') != "true") {
                if(aType == "all") r.push(childs[i]);
                else if(aType == "local" && childs[i].getAttribute('remote') == "false") r.push(childs[i]);
                else if(aType == "remote" && childs[i].getAttribute('remote') == "true") r.push(childs[i]);
            }
        }
        
        return r;

    };


    // Clean up
    this.shutdown = function() {

        window.removeEventListener("DOMContentLoaded", AiOS_Addons.initialize, false);
        window.removeEventListener("load", AiOS_Addons.setDetailLayout, false);
        window.removeEventListener("unload", AiOS_Addons.shutdown, false);

    };

    // Register handlers to maintain extension life cycle.
    window.addEventListener("DOMContentLoaded", this.initialize, false);
    window.addEventListener("load", this.setDetailLayout, false);
    window.addEventListener("unload", this.shutdown, false);

}).apply(AiOS_Addons);



